package com.kuiandjie.web;


import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.google.gson.Gson;
import com.kuiandjie.entity.Contact;
import com.kuiandjie.entity.ContactNoteMsg;
import com.kuiandjie.entity.Project;
import com.kuiandjie.service.ConcatService;
import com.kuiandjie.service.ContactNoteService;

public class ContactServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;
	
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session = request.getSession();
		Project curp = (Project) session.getAttribute("curp");
		
		if(curp != null && "POST".equals(request.getMethod())) {
			
			int id = Integer.parseInt(request.getParameter("id"));
			String m = request.getParameter("m");
			
			if("get".equals(m)) {
				response.setContentType("application/json;charset=UTF-8");
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				ContactNoteMsg cnm = new ContactNoteMsg();
				cnm.setContact(new ConcatService().findContactById(id));
				cnm.setList(new ContactNoteService().findByContactId(id));
				
				System.out.println(new Gson().toJson(cnm));
				out.print(new Gson().toJson(cnm));
				out.flush();
				out.close();
				
				return;
			} else if("delete".equals(m)) {
				/*//删除功能不适用
				response.setContentType("text/html");
				response.setCharacterEncoding("UTF-8");
				PrintWriter out = response.getWriter();
				
				new ConcatService().deleteById(id);
				
				out.print("10001");
				out.flush();
				out.close();
				
				return;*/
			}
		}
		
		if(curp != null) {
			List<Contact> list = new ConcatService().findContactByProjectId(curp.getId());
			request.setAttribute("contact", list);
			request.getRequestDispatcher("WEB-INF/views/contact.jsp").forward(request, response);
		} else {
			response.sendRedirect("project.jspx");
		}
		
	}
}
